package ths

import (
	"fmt"
	"gitee.com/gcom/gbox/errors"
	"gitee.com/gcom/stockdock/comm"
	s "gitee.com/gcom/stockdock/core/support"
	"gitee.com/gcom/stockdock/crawler"
	"gitee.com/gcom/stockdock/spider/csrc"
	"gitee.com/gcom/stockdock/spider/ths"
)

func UpdateCompany(ctx s.TracerCtx) error {
	list, err := csrc.GetStockAll(ctx.DB)
	if err != nil {
		s.WriteErrEvent(ctx, "查询股票错误", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("共有%d条，开始同步上市企业信息", len(list)))

	var fail = 0
	cctx, cancel := crawler.NewChromedpCtx(ctx, 0, nil)
	defer cancel()
	_, err = comm.DoWithPartition(len(list), 50, func(low, high int) error {
		var entities []*ths.CompanyThsEntity
		for i := low; i < high; i++ {
			comp, err := ths.GetCompInfoThs(cctx, list[i].Code)
			if err != nil {
				fail += 1
				ctx.Logger.Errorf("获取企业信息错误，%s %s：%w", list[i].Code, list[i].Name, err)
			}
			if fail >= 10 {
				return errors.New(fmt.Sprintf("获取企业信息失败已达%d条，放弃执行", fail))
			}
			ctx.Logger.Infof("已获取企业信息：%d/%d, %s %s", i, len(list), list[i].Code, list[i].Name)
			entities = append(entities, &ths.CompanyThsEntity{CompInfoThs: comp})
		}
		_, err := ths.UpdateCompanyThs(ctx.DB, entities)
		if err != nil {
			ctx.Logger.Errorf("写入企业信息错误%v", err)
			return err
		}
		s.WriteEvent(ctx, fmt.Sprintf("更新企业信息: %d/%d，失败: %d条", high, len(list), fail))
		return nil
	})
	if err != nil {
		s.WriteErrEvent(ctx, errors.Cause(err).Error(), err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("刷新完成，成功: %d/%d, 失败: %d", len(list)-fail, fail))
	return nil
}
